# from datetime import datetime, time
import json

from forms import StoreForm, NewStoreForm, SearchStudentForm, SearchBookForm, AdminViolationForm, LogoffForm
from flask import Blueprint, render_template, request, url_for, session, jsonify, flash, redirect, g
from models import BookModel, InventoryModel, BorrowModel, UserModel, InterloanBookModel, DetailModel,LetterModel
from exts import db
import time, datetime
from forms import StoreForm, InterLoanForm
from utils import SendSmsRequest, send_sms, userViolation
from bluePrints.user import timestamp

import uuid
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.profile import region_provider
from aliyunsdkcore.request import RpcRequest

book = Blueprint('book', __name__)


@book.route('/book/smsSend', methods=['GET', 'POST'])
def smsSend():
    accounts = json.loads(request.get_data())
    phones = []
    for account in accounts:
        phones.append(account['phone'])
    phones = list(set(phones))
    for phone in phones:
        print(phone)
        # 解注释即可发短信
        # send_sms(phone, "{'code':'你于5.1借阅的百年孤独逾期未归还，请于5.2下午17.30之前归还！'}")
    return jsonify(phones)


@book.route('/book/storage', methods=['GET', 'POST'])
def storage():
    if request.method == 'GET':
        form = StoreForm()
        return render_template('storage.html', form=form)
    elif request.method == 'POST':
        form = StoreForm()
        if form.validate_on_submit():
            book = BookModel.query.filter_by(isbn=request.form.get('isbn')).first()
            exist = InventoryModel.query.filter_by(barcode=request.form.get('barcode')).first()
            if book is None:
                flash(u'添加失败，请注意本书信息是否已经录入，若未登记，请在‘新书入库’窗口登入信息')
            else:
                if len(request.form.get('barcode')) != 6:
                    flash(u'图书编码长度错误')
                else:
                    if exist is not None:
                        flash(u'该编号已经存在！')
                    else:
                        inventory = InventoryModel()
                        inventory.barcode = request.form.get('barcode')
                        inventory.isbn = request.form.get('isbn')
                        inventory.admin_id = g.account.id
                        inventory.number = request.form.get('number')
                        inventory.borrowable_number = request.form.get('number')
                        inventory.location = request.form.get('location')
                        inventory.status = True
                        inventory.withdraw = False
                        today_date = datetime.date.today()
                        today_str = today_date.strftime("%Y-%m-%d")
                        today_stamp = time.mktime(time.strptime(today_str + ' 00:00:00', '%Y-%m-%d %H:%M:%S'))
                        inventory.storage_date = int(today_stamp) * 1000
                        db.session.add(inventory)
                        db.session.commit()
                        flash(u'入库成功！')
            return redirect(url_for('book.storage'))
        return render_template('storage.html', form=form)


@book.route('/book/new_store', methods=['GET', 'POST'])
def new_store():
    if request.method == 'GET':
        form = NewStoreForm()
        return render_template('new-store.html', form=form)
    elif request.method == 'POST':
        form = NewStoreForm()
        if form.validate_on_submit():
            if len(request.form.get('isbn')) != 13:
                flash(u'ISBN长度错误')
            else:
                exist = BookModel.query.filter_by(isbn=request.form.get('isbn')).first()
                if exist is not None:
                    flash(u'该图书信息已经存在，请核对后再录入，或者填写入库表')
                else:
                    book = BookModel()
                    book.isbn = request.form.get('isbn')
                    book.book_name = request.form.get('book_name')
                    book.press = request.form.get('press')
                    book.author = request.form.get('author')
                    book.type = request.form.get('class_name')
                    book.price = request.form.get('price')
                    book.isLib = 1
                    db.session.add(book)
                    db.session.commit()
                    flash(u'图书信息添加成功')
            return redirect(url_for('book.storage'))
        return render_template('new-store.html', form=form)


@book.route('/book/borrow', methods=['GET', 'POST'])
def borrow():
    return render_template('borrow.html')


@book.route('/book/return', methods=['GET', 'POST'])
def return_book():
    return render_template('return.html')


@book.route('/book/find_stu_book', methods=['GET', 'POST'])
def find_stu_book():
    today_date = datetime.date.today()
    today_str = today_date.strftime("%Y-%m-%d")
    today_stamp = time.mktime(time.strptime(today_str + ' 00:00:00', '%Y-%m-%d %H:%M:%S'))
    data = [today_stamp]
    return jsonify(data)


@book.route('/book/find_not_return_book', methods=['GET', 'POST'])
def find_not_return_book():
    data = []
    return jsonify(data)


@book.route('/book/change_info', methods=['GET', 'POST'])
def change_info():
    return render_template('change-info.html')


@book.route('/book/search_book', methods=['GET', 'POST'])
def search_book():  # 这个函数里不再处理提交按钮，使用Ajax局部刷新
    if request.method == 'GET':
        form = SearchBookForm()
        return render_template('search-book.html', form=form)


@book.route('/book/search_student', methods=['GET', 'POST'])
def search_student():
    if request.method == 'GET':
        form = SearchStudentForm()
        return render_template('search-student.html', form=form)


@book.route('/books', methods=['GET', 'POST'])
def find_book():
    if request.method == 'GET':
        books = db.session.query(BookModel).join(InventoryModel).filter(InventoryModel.withdraw == False).all()
        data = []
        for book in books:
            inventories = InventoryModel.query.filter_by(isbn=book.isbn, status=True).all()
            for inventory in inventories:
                item = {'isbn': book.isbn, 'book_name': book.book_name, 'press': book.press, 'author': book.author,
                        'class_name': book.type, 'location': inventory.location, 'count': inventory.number,
                        'available': inventory.borrowable_number}
                data.append(item)
        return jsonify(data)
    elif request.method == 'POST':
        def find_name():
            return db.session.query(BookModel).join(InventoryModel).filter(
                BookModel.book_name.like('%' + request.form.get('content') + '%'),
                InventoryModel.withdraw == False).all()
            # return BookModel.query.filter(BookModel.book_name.like('%' + request.form.get('content') + '%')).all()

        def find_author():
            return db.session.query(BookModel).join(InventoryModel).filter(
                BookModel.author.contains(request.form.get('content')), InventoryModel.withdraw == False).all()
            # return BookModel.query.filter(BookModel.author.contains(request.form.get('content'))).all()

        def find_class():
            return db.session.query(BookModel).join(InventoryModel).filter(
                BookModel.type.contains(request.form.get('content')), InventoryModel.withdraw == False).all()
            # return BookModel.query.filter(BookModel.type.contains(request.form.get('content'))).all()

        def find_isbn():
            return db.session.query(BookModel).join(InventoryModel).filter(
                BookModel.isbn.contains(request.form.get('content')), InventoryModel.withdraw == False).all()
            # return BookModel.query.filter(BookModel.isbn.contains(request.form.get('content'))).all()

        methods = {
            'book_name': find_name,
            'author': find_author,
            'class_name': find_class,
            'isbn': find_isbn
        }
        books = methods[request.form.get('method')]()
        data = []
        for book in books:
            inventories = InventoryModel.query.filter_by(isbn=book.isbn, status=True).all()
            for inventory in inventories:
                item = {'isbn': book.isbn, 'book_name': book.book_name, 'press': book.press, 'author': book.author,
                        'class_name': book.type, 'location': inventory.location, 'count': inventory.number,
                        'available': inventory.borrowable_number}
                data.append(item)
        return jsonify(data)


@book.route('/interloan_books', methods=['POST'])
def find_interloan_book():
    def find_name():
        return db.session.query(BookModel).join(InventoryModel).join(InterloanBookModel).filter(
            BookModel.book_name.like('%' + request.form.get('content') + '%'),
            InventoryModel.withdraw == False, BookModel.isLib == 0).all()

    def find_author():
        return db.session.query(BookModel).join(InventoryModel).filter(
            BookModel.author.contains(request.form.get('content')), InventoryModel.withdraw == False,
                                                                    BookModel.isLib == 0).all()

    def find_class():
        return db.session.query(BookModel).join(InventoryModel).filter(
            BookModel.type.contains(request.form.get('content')), InventoryModel.withdraw == False,
                                                                  BookModel.isLib == 0).all()

    def find_isbn():
        return db.session.query(BookModel).join(InventoryModel).filter(
            BookModel.isbn.contains(request.form.get('content')), InventoryModel.withdraw == False,
                                                                  BookModel.isLib == 0).all()

    methods = {
        'book_name': find_name,
        'author': find_author,
        'class_name': find_class,
        'isbn': find_isbn
    }
    books = methods[request.form.get('method')]()
    data = []
    for book in books:
        lenders = InterloanBookModel.query.filter_by(isbn=book.isbn).all()
        for lender in lenders:
            item = {'isbn': book.isbn, 'book_name': book.book_name, 'press': book.press, 'author': book.author,
                    'class_name': book.type, 'fee': book.price, 'lender': lender.lender}
            data.append(item)
    return jsonify(data)


@book.route('/book/logoff', methods=['GET', 'POST'])
def logoff():
    if request.method == 'GET':
        form = LogoffForm()
        return render_template('book-logoff.html', form=form)
    if request.method == 'POST':
        form = LogoffForm()
        if form.validate_on_submit():
            inventories = InventoryModel.query.filter_by(isbn=form.isbn.data, withdraw=False).all()
            if inventories is None or inventories == []:
                flash(u'请输入正确的isbn号！')
                return render_template('book-logoff.html', form=form)
            else:
                for inventory in inventories:
                    inventory.withdraw = True
                db.session.commit()
                flash(u'注销成功!')
                return redirect(url_for('book.logoff'))
        return render_template('book-logoff.html', form=form)


@book.route('/book/system_message', methods=['GET', 'POST'])
def system_message():
    return render_template('system-message.html')


@book.route('/book/reader_letter', methods=['GET', 'POST'])
def reader_letter():
    return render_template('reader-letter.html')


@book.route('/book/overdate_violation', methods=['GET', 'POST'])
def overdate_violation():
    # 传入数据库查询的用户违规记录并渲染
    username = g.account.username
    today_date = datetime.date.today()
    today_str = today_date.strftime("%Y-%m-%d")
    str_today_stamp = time.mktime(time.strptime(today_str + ' 00:00:00', '%Y-%m-%d %H:%M:%S'))
    today_stamp = int(str_today_stamp) * 1000
    violations = db.session.query(BorrowModel).join(UserModel).join(BookModel).filter(
        BorrowModel.return_time == None, UserModel.username == username
    ).with_entities(BookModel.book_name,
                    BorrowModel.due_date).all()

    items = []
    for violation in violations:
        due_date = timestamp(violation.due_date)
        item = {'due_date': due_date, 'book_name': violation.book_name}
        items.append(item)
    return render_template('overdate-violation.html', items=items)


@book.route('/book/admin_violation', methods=['GET', 'POST'])
def admin_violation():
    if request.method == 'GET':
        form = AdminViolationForm()
        return render_template('admin-violation.html', form=form)


@book.route('/book/detail_message/<id>', methods=['GET', 'POST'])
def detail_message(id):
    detail = db.session.query(DetailModel).filter(
        DetailModel.id == id
    ).with_entities(DetailModel.author, DetailModel.dept, DetailModel.title,
                    DetailModel.para1, DetailModel.para2, DetailModel.para3, DetailModel.para4, DetailModel.para5,
                    DetailModel.para6).all()
    return render_template('detail-message.html', detail=detail)

@book.route('/book/detail_letter/<id>', methods=['GET', 'POST'])
def detail_letter(id):
    letter = db.session.query(LetterModel).filter(
        LetterModel.id == id
    ).with_entities(LetterModel.author, LetterModel.dept, LetterModel.title, LetterModel.para1).all()
    return render_template('detail-letter.html', letter=letter)

@book.route('/book/recommend_book', methods=['GET', 'POST'])
def recommend_book():
    if request.method == 'GET':
        list=[0,0,0,0,0,0,0,0]
        l2=[0,0,0,0,0,0,0,0,0]
        a = g.account.card_id
        b=0
        bo1s = BorrowModel.query.filter_by(card_id=a).all()
        bo11 = BorrowModel.query.filter_by(card_id=a).first()
        if bo11.id=='':
               context = {
                   'bookname': "白夜行",
                   'author': "东野圭吾",
                   'press': 1234567890124,
                   'bookname2': "高等数学",
                   'author2': "任叶庆",
                   'press2': 1357924681012,
                   'bookname3': "挪威的森林",
                   'author3': "村上春树",
                   'press3': 1234567890133,
                   'bookname4': "罗生门",
                   'author4': "芥川龙之介",
                   'press4': 1234567890132,
               }
        else:
               for bo1 in bo1s:
                   bk1 = BookModel.query.filter_by(isbn=bo1.book_id).first()
                   l2[b] = bo1.book_id
                   b = b + 1
                   # 根据数据类型推荐：
                   # 加权赋推荐值
                   if bk1.type == '奇幻':  # 0
                       list[0] = list[0] + 1
                       list[1] = list[1] + 0.3
                       list[2] = list[2] + 0.8
                   elif bk1.type == '爱情':  # 1
                       list[1] = list[1] + 1
                       list[0] = list[0] + 0.5
                       list[2] = list[2] + 0.5
                   elif bk1.type == '魔幻':  # 2
                       list[2] = list[2] + 1
                       list[0] = list[0] + 0.8
                       list[1] = list[1] + 0.3
                   elif bk1.type == '悬疑':  # 3
                       list[3] = list[3] + 1
                       # list[0] = list[0] + 0.5
                   elif bk1.type == '文学':  # 4
                       list[4] = list[4] + 1
                       list[6] = list[6] + 0.7
                       list[5] = list[5] + 0.2
                   elif bk1.type == '现实':  # 5
                       list[5] = list[5] + 1
                       list[4] = list[4] + 0.5
                   elif bk1.type == '诗集':  # 6
                       list[6] = list[6] + 1
                       list[4] = list[4] + 0.7
                       list[5] = list[5] + 0.5
               # 排序书籍类型来推荐
               l = ["奇幻", "爱情", "魔幻", "悬疑", "文学", "现实", "诗集"]
               length = len(list)
               for i in range(1, length):
                   for j in range(0, length - i):
                       if list[j] < list[j + 1]:
                           temp = list[j]
                           temp2 = l[j]  # 标识符修改
                           list[j] = list[j + 1]
                           l[j] = l[j + 1]  # 标识符修改
                           list[j + 1] = temp
                           l[j + 1] = temp2  # 标识符修改
               # 根据大小输出排名和类型
               # for i in range(0, 7):
               #     print(list[i],l[i])
               # 设置循环开始推荐
               d = 0
               h = 0
               listname = ["暂无", "暂无", "暂无", "暂无", "暂无", "暂无", "暂无","暂无", "暂无", "暂无", "暂无", "暂无"]
               listid = ["暂无", "暂无", "暂无", "暂无", "暂无", "暂无", "暂无","暂无", "暂无", "暂无", "暂无", "暂无"]
               listauthor = ["暂无", "暂无", "暂无", "暂无", "暂无","暂无", "暂无", "暂无", "暂无", "暂无", "暂无", "暂无"]
               for i in range(0, 3):
                   bk2s = BookModel.query.filter_by(type=l[i]).all()
                   for bk2 in bk2s:
                       for c in range(0, 5):
                           if bk2.isbn == l2[c]:
                               break
                       # print(bk2.book_name)
                       d = d + 1
                       listname[h] = bk2.book_name
                       listid[h] = bk2.isbn
                       listauthor[h] = bk2.author
                       h = h + 1
                       if d >= 4 - i:
                           break
               context = {
                   'bookname': listname[0],
                   'author': listauthor[0],
                   'press': listid[0],
                   'bookname2': listname[1],
                   'author2': listauthor[1],
                   'press2': listid[1],
                   'bookname3': listname[2],
                   'author3': listauthor[2],
                   'press3': listid[2],
                   'bookname4': listname[3],
                   'author4': listauthor[3],
                   'press4': listid[3],
                   'bookname5': listname[4],
                   'author5': listauthor[4],
                   'press5': listid[4]
               }



        return render_template('recommend.html',**context)


@book.route('/book/find_violation', methods=['GET', 'POST'])
def find_violation():
    if request.method == 'POST':
        # 从数据库查询username(user),sex(user),debt(user),book_name(book),author(book),borrow_time,return_time,due_time
        violations = db.session.query(BorrowModel).join(UserModel).join(BookModel).filter(
            BorrowModel.return_time == None, UserModel.username.contains(request.form.get('username'))
        ).with_entities(UserModel.username, UserModel.valid_date, UserModel.debt,
                        BookModel.author, BookModel.book_name,
                        BorrowModel.return_time, BorrowModel.due_date, BorrowModel.borrow_time, UserModel.phone).all()
        data = []
        for violation in violations:
            borrow_time = timestamp(violation.borrow_time)
            return_time = timestamp(violation.return_time)
            due_date = timestamp(violation.due_date)
            valid_date = timestamp(violation.valid_date)
            if return_time is None:
                return_time = '未归还'
            item = {'username': violation.username, 'valid_time': valid_date, 'debt': violation.debt,
                    'book_name': violation.book_name, 'author': violation.author,
                    'start_date': borrow_time, 'due_date': due_date, 'end_date': return_time, 'phone': violation.phone}
            data.append(item)
        return jsonify(data)
    elif request.method == 'GET':
        violations = db.session.query(BorrowModel).join(UserModel).join(BookModel).filter(
            BorrowModel.return_time == None
        ).with_entities(UserModel.username, UserModel.valid_date, UserModel.debt,
                        BookModel.author, BookModel.book_name,
                        BorrowModel.return_time, BorrowModel.due_date, BorrowModel.borrow_time, UserModel.phone).all()
        data = []
        for violation in violations:
            borrow_time = timestamp(violation.borrow_time)
            return_time = timestamp(violation.return_time)
            due_date = timestamp(violation.due_date)
            valid_date = timestamp(violation.valid_date)
            if return_time is None:
                return_time = '未归还'
            item = {'username': violation.username, 'valid_time': valid_date, 'debt': violation.debt,
                    'book_name': violation.book_name, 'author': violation.author,
                    'start_date': borrow_time, 'due_date': due_date, 'end_date': return_time, 'phone': violation.phone}
            data.append(item)
        return jsonify(data)


@book.route('/book/interloan', methods=['GET', 'POST'])
def interloan():
    if request.method == 'GET':
        form = InterLoanForm()
        return render_template('interloan.html', form=form)


@book.route('/book/new_interloan', methods=['GET', 'POST'])
def new_interloan():
    if request.method == 'GET':
        form = NewStoreForm()
        return render_template('new-interloan.html', form=form)
    elif request.method == 'POST':
        form = NewStoreForm()
        if form.validate_on_submit():
            if len(request.form.get('isbn')) != 13:
                flash(u'ISBN长度错误')
            else:
                exist = BookModel.query.filter_by(isbn=request.form.get('isbn')).first()
                if exist is not None:
                    flash(u'图书信息登记成功，请前往前台交付图书')
                else:
                    book = BookModel()
                    book.isbn = request.form.get('isbn')
                    book.book_name = request.form.get('book_name')
                    book.press = request.form.get('press')
                    book.author = request.form.get('author')
                    book.type = request.form.get('class_name')
                    book.price = request.form.get('price')
                    book.isLib = 0
                    db.session.add(book)
                    db.session.commit()
                    book_interloan = InterloanBookModel()
                    book_interloan.isbn = request.form.get('isbn')
                    book_interloan.lender = g.account.username
                    book_interloan.state = 1
                    db.session.add(book_interloan)
                    db.session.commit()
                    flash(u'图书信息登记成功,请前往前台交付图书')
                return redirect(url_for('book.interloan'))
        return render_template('new-interloan.html', form=form)

